package com.lhq.tag_tales.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhq.tag_tales.common.BaseResponse;
import com.lhq.tag_tales.common.ErrorCodeEnum;
import com.lhq.tag_tales.exception.BusinessException;
import com.lhq.tag_tales.model.domain.User;
import com.lhq.tag_tales.model.domain.request.UserLoginRequest;
import com.lhq.tag_tales.service.UserService;
import com.lhq.tag_tales.utils.UserUtils;
import com.lhq.user_center_backend.model.domain.request.UserRegisterRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册接口
     *
     * @param userRegisterRequest 用户注册请求对象，包含用户账号、密码、确认密码和星球代码
     * @return 返回注册成功后的用户ID
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "注册信息存在空值");
        }
        long userId = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return BaseResponse.success(userId);
    }

    /**
     * 推荐用户接口
     *
     * @param pageSize 每页显示的用户数量
     * @param pageNum  当前页数
     * @return 返回推荐的用户列表
     */
    @PostMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum) {
        Page<User> userPage = userService.recommendUser(pageSize, pageNum);
        return BaseResponse.success(userPage);
    }


    /**
     * 获取当前登录用户接口
     *
     * @return 返回当前登录用户信息
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser() {
        User currentUser = UserUtils.getCurrentUser();
        //校验用户是否存在
        if (currentUser == null) {
            throw new BusinessException(ErrorCodeEnum.NO_LOGIN, "未登录");
        }
        //校验用户是否通过了校验
        Integer isValid = currentUser.getIsValid();
        if (isValid.equals(0)) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH, "账号未通过审核");
        }
        return BaseResponse.success(userService.getSafetyUser(currentUser));
    }


    /**
     * 用户登录接口
     *
     * @param userLoginRequest 用户登录请求对象，包含用户账号和密码
     * @param request          HTTP请求对象，用于保存会话信息
     * @return 返回登录成功的用户信息
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info("sessionId为{}", request.getSession().getId());
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "账号或密码为空");
        }
        return BaseResponse.success(userService.userLogin(userAccount, userPassword, request));
    }

    /**
     * 管理员查询用户接口
     *
     * @param userName 查询的用户名
     * @return 返回查询到的用户列表
     */
    @GetMapping
    public BaseResponse<List<User>> searchUsers(String userName) {
        if (!userService.isAdmin()) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH, "权限不足");
        }
        // 仅管理员可查询
        List<User> userList = userService.searchUsers(userName);
        List<User> collect = userList.stream().map(userService::getSafetyUser).collect(Collectors.toList());
        return BaseResponse.success(collect);
    }

    /**
     * 管理员删除用户接口
     *
     * @param id      要删除的用户ID
     * @return 返回删除操作的结果
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestParam Long id) {
        if (!userService.isAdmin()) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH, "权限不足");
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "请指定删除用户的id");
        }
        userService.deleteUserById(id);
        return BaseResponse.success();
    }


    /**
     * 用户注销接口
     *
     * @param request HTTP请求对象，用于清除会话信息
     * @return 返回注销操作的结果
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        return BaseResponse.success(userService.userLogout(request));
    }

    /**
     * 根据标签查询用户接口
     *
     * @param tagNameList 查询的标签列表
     * @return 返回查询到的用户列表
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> getUsersByTags(@RequestParam List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCodeEnum.PARAMS_ERROR, "标签列表为空");
        }
        List<User> userList = userService.searchUsersByTags(tagNameList)
                .stream()
                .map(userService::getSafetyUser)
                .collect(Collectors.toList());
        return BaseResponse.success(userList);
    }

    /**
     * 更新用户信息接口
     *
     * @param updateUser    更新的用户信息
     * @return 返回更新操作的结果
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User updateUser) {
        //判断是否为管理员或用户自己
        User currentUser = UserUtils.getCurrentUser();
        int row = userService.updateUser(updateUser, currentUser);
        return BaseResponse.success(row);
    }
}
